package com.mgy.api.framework.core.adapter;


import com.mgy.api.framework.core.annotation.Adapter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * AdapterFactory
 *
 * @author mgy
 * @date 2019.10.20
 */
public class AdapterFactory {

    private static final ConcurrentMap<String, Object> INSTANCE_MAP = new ConcurrentHashMap<>();

    public static <T> T getInstance(Class<T> type, String source) {
        Map<String, T> maps = ApplicationContextUtil.getApplicationContext().getBeansOfType(type);
        if (maps.isEmpty()) {
            throw new IllegalArgumentException("找不到对应的实例type=" + type.getName() + ";source=" + source);
        }
        String key = source + "_" + type.getName();

        Object t = INSTANCE_MAP.get(key);
        if (t != null) {
            return type.cast(t);
        }
        for (T obj : maps.values()) {
            Adapter adapter = AnnotationUtils.findAnnotation(obj.getClass(), Adapter.class);
            if (adapter != null && contains(adapter.value(), source)) {
                T instance = type.cast(obj);
                INSTANCE_MAP.putIfAbsent(key, instance);
                return instance;
            }
        }
        throw new IllegalArgumentException("找不到对应的实例type=" + type.getName() + ";source=" + source);
    }

    private static boolean contains(String[] sourceArr, String source) {
        if (sourceArr == null || StringUtils.isEmpty(source)) {
            return false;
        }
        for (String s : sourceArr) {
            if (source.equals(s)) {
                return true;
            }
        }
        return false;
    }

}
